<?php
namespace Home\Controller;
class ViewController extends BaseController {
    /**
     * 进入聊天页面
     */
    public function index(){
        $classid = I('classid',0,'intval');
        $userinfo = M("User")->field("id,nickname,headimgurl,status")->find($this->_userid);
        $this->assign('userinfo',$userinfo);
        $current = strtotime(date("Y-m-d"));
        $msg_list = D("MsgView")->where(array('createtime'=>array('gt',$current)))->order("createtime asc")->select();
        if (!empty($msg_list) && is_array($msg_list)){
            $msg_info = end($msg_list);
            session('msg_id',$msg_info['id']);
        }else{
            session('msg_id',0);
        }
        //@列表参与该课程的所有成员（自己除外）
        $user_list = M('User')->field("id,nickname,headimgurl")->where(array('id'=>array('neq',$this->_userid)))->select();
        //是否禁言
        session("only_id",0);
        $ban_speech = $this->relation($classid);
        $this->assign('classid',$classid);
        $this->assign('ban_speech',$ban_speech);
        $this->assign('user_list',$user_list);
        $this->assign('signPackage',$this->getSignPackage());
        $this->assign('msg_list',$msg_list);
        $this->display();
    }
    
    /**
     * 只看主讲
     */
    public function only_speech(){
        session("only_id",1);
        $html = "";
        $current = strtotime(date("Y-m-d"));
        $msg_list = D("MsgView")->where(array('createtime'=>array('gt',$current),'status'=>array('neq',1)))->select();
        $id = 0;
        foreach ($msg_list as $key=>$val){
            $html.=$this->show_msg($val);
            $id = $val['id'];
        }
        session('msg_id',$id);
        echo $html;
    }
    
    /**
     * 即使更改状态
     */
    public function immediately_status(){
        $classid = I('classid',0,'intval');
        header('Content-Type: text/event-stream');
        header('Cache-Control: no-cache');
        if ($classid){
            $html = $this->relation($classid);
            echo "data: {$html}\n\n";
            flush();
        }else{
        echo "data:  \n\n";
        }
        
    }
    
    /**
     * 更改状态
     */
    public function speech_status(){
        $classid = I('classid',0,'intval');
        $ban_speech = I('ban_speech',0,'intval');
        $rel_id = M('Relation')->getFieldByClass_id($classid,'id');
        $result = M('Relation')->where(array('id'=>$rel_id))->setField('ban_speech',$ban_speech);        
        echo $result?1:2;        
    }
    
    
    /**
     * 保存语音信息
     */
    public function save_voice_msg(){
        $accessToken =$this->getAccessTokenDown();
        $media_id =I('media_id');
        $time = I('time',0,'intval');
        $voice_width = number_format($time/60+30, 2, '.', '').'%';
        //下载
     
        $path="./Public/uploads/voice/{$this->_openid}/".date('Ymd',time()).'/';
        mkdirs($path); //创建文件夹
        $filename=$path.date('YmdHis').'.amr';
        $voice_url = "http://file.api.weixin.qq.com/cgi-bin/media/get?access_token={$accessToken}&type=image&media_id={$media_id}";
        $Http = new \Org\Net\Http;//http下载图片
        $Http::curlDownload($voice_url,$filename);
        
        
        $data = array(
            'user_id'=>$this->_userid,
            'media_id'=>$media_id,
            'msg_type'=>2,
            'time'=>$time,
            'voice_width'=>$voice_width,
            'createtime'=>time(),
            'voice'=>$filename
        );
        $this->add_info($data);
    }
    
    /**
     * 保存图片信息
     */
    public function save_img_msg(){
        $accessToken =$this->getAccessTokenDown();
        $media_id =I('media_id');
        $path="./Public/uploads/images/{$this->_openid}/".date('Ymd',time()).'/';
        mkdirs($path); //创建文件夹
        $filename=$path.date('YmdHis').'.jpg';
        $pic_url = "http://file.api.weixin.qq.com/cgi-bin/media/get?access_token={$accessToken}&type=image&media_id={$media_id}";
        $Http = new \Org\Net\Http;//http下载图片
        $Http::curlDownload($pic_url,$filename);
        $data = array(
            'user_id'=>$this->_userid,
            'image_url'=>'http://'.$_SERVER['SERVER_NAME'].substr($filename,1),
            'msg_type'=>3,
            'createtime'=>time()
        );
        $this->add_info($data);
    }
    
    /**
     * 保存文本消息
     */
    public function save_text_msg(){
        $msg = I('msg','','strval');
        $data = array(
            'user_id'=>$this->_userid,
            'message'=>$msg,
            'msg_type'=>1,
            'createtime'=>time()
        );
        $this->add_info($data);
    }
    
    /**
     * 服务器发送消息
     */
    public function send_msg(){
        header('Content-Type: text/event-stream');
        header('Cache-Control: no-cache');
        $id = session('msg_id');
        $only_id = session("only_id");
        if ($id){
            $html = "";
            if($only_id){
                $msg_list = D("MsgView")->where(array('id'=>array('gt',$id),'status'=>array('neq',1)))->select();
            }else{
                $msg_list = D("MsgView")->where(array('id'=>array('gt',$id)))->select();
            }
            foreach ($msg_list as $key=>$val){
                $html.=$this->show_msg($val);
                $id = $val['id'];
            }
            session('msg_id',$id);
            echo "data: {$html}\n\n";
            flush();
        }else{
            echo "data:  \n\n";
        }
    }
    
    /**
     * 获取是否禁言
     */
    private function relation($class_id = 0){
        $ban_speech = M("Relation")->getFieldByClass_id($class_id,'ban_speech');
        return intval($ban_speech);
    }
    
    //下载微信文件
    private function downloadWeixinFile($url)
    {
        $ch = curl_init($url);
        curl_setopt($ch, CURLOPT_HEADER, 0);    
        curl_setopt($ch, CURLOPT_NOBODY, 0);    //只取body头
        curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, FALSE);
        curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, FALSE);
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
        $package = curl_exec($ch);
        $httpinfo = curl_getinfo($ch);
        curl_close($ch);
        $imageAll = array_merge(array('header' => $httpinfo), array('body' => $package)); 
        return $imageAll;
    }
    
    //保存微信文件
    private function saveWeixinFile($filename, $filecontent)
    {
        $local_file = fopen($filename, 'w');
        if (false !== $local_file){
            if (false !== fwrite($local_file, $filecontent)) {
                fclose($local_file);
            }
        }
    }
    
    //添加信息
    private function add_info($data){
        $insert_id = M("Message")->add($data);
        if ($insert_id){
            $msg_val = D("MsgView")->where(array('id'=>$insert_id))->find();
            if ($msg_val['user_id']==$this->_userid){
                session('msg_id',$insert_id+1);
            }else{
                session('msg_id',$insert_id);
            }
            echo json_encode($msg_val);
        }else{
            echo null;
        }
    }
    
    //展示消息
    private function show_msg($msg = array()){
        $html = "";
        if($msg['status'] == 3){
            $role = '(主持人)';
        }elseif($msg['status'] == 2){
            $role = '(导师)';
        }
        $type = $msg['msg_type'];
        switch ($type){
            case 1:
                    $html.='<div class="qb-chat-box qb-receiver" data-uuid="'.$msg['id'].'">';
                    $html.='<div class="qb-chat-img" data-uuid="'.$msg['user_id'].'"><img src="'.$msg['headimgurl'].'"></div>';
                    $html.='<div class="qb-chat-message-box">';
                    $html.='<div class="qb-chat-name">'.$msg['nickname'].$role;
                    $html.='</div>';
                    $html.='<div class="qb-chat-cont"><span class="qb-mess">'.$msg['message'].'</span></div>';
                    $html.='</div>';
                    $html.='</div>';
                break;
            case 2:
                    $html.='<div class="qb-chat-box qb-receiver" data-fuuid="'.$msg['id'].'" data-time="'.$msg['time'].'" data-voiceurl="">'.
                        '<div class="qb-chat-img"  data-uuid="'.$msg['user_id'].'"><img src="'. $msg['headimgurl'].'"></div>' .
                        '<div class="qb-chat-message-box">'.
    					'<div class="qb-chat-name">'.$msg['nickname'].$role.
    					'</div>'.
						'<div class="qb-chat-cont qb-mess-voice" style="width:'.$msg['voice_width'].';">'.
	                    '<audio src="'.$msg['media_id'].'" preload="none"></audio>'.
	                    '<div class="qb-affiliated"><b class="qb-noread"></b><span class="qb-voicetime">'.$msg['time'].'"</span></div>'.
	                    '<span class="qb-mess">'.
                    	'<div class="qb-voice"></div>'.
                    	'</span>'.
	                    '</div>'.
	    				'</div>'.
                        '</div>';
                break;
            case 3:
                    $html.='<div class="qb-chat-box qb-receiver" data-uuid="'.$msg['id'].'">'.
                        '<div class="qb-chat-img"  data-uuid="'.$msg['user_id'].'"><img src="'.$msg['headimgurl'].'"></div>'.
                        '<div class="qb-chat-message-box">'.
                        '<div class="qb-chat-name">'.$msg['nickname'].$role.'</div>'.
                        '<div class="qb-chat-cont-img"><span class="qb-mess"><img src="' . $msg['image_url'] . '"></span></div>'.
                        '</div>'.
                        '</div>';
                break;
        }
        return $html;
    }
}
?>